import React, { useEffect, useRef, useState } from 'react'
import {
  Box,
  Text,
  Flex,
  Badge,
  VStack,
  HStack,
  Button
} from '@chakra-ui/react'

export interface LogEntry {
  id: string
  timestamp: Date | string
  level: 'info' | 'warn' | 'error' | 'debug' | 'success'
  message: string
  source?: string // 添加日志源信息，如 "general_tools:wait:59"
}

interface LogBoxProps {
  logs: LogEntry[] | string[] // 支持 LogEntry 数组或字符串数组
  maxHeight?: string
  autoScroll?: boolean
  showTimestamp?: boolean
  showLevel?: boolean
  showSource?: boolean // 是否显示日志源
  filterLevel?: LogEntry['level'][]
}

const LogBox: React.FC<LogBoxProps> = ({
  logs,
  maxHeight = '400px',
  autoScroll = true,
  showTimestamp = true,
  showLevel = true,
  showSource = true,
  filterLevel
}) => {
  const containerRef = useRef<HTMLDivElement>(null)
  const [isUserScrolling, setIsUserScrolling] = useState(false)

  // 解析日志字符串
  const parseLogString = (logString: string, index: number): LogEntry => {
    // 匹配格式: 2025-08-12 09:30:23.8138 |general_tools:wait:59| INFO | message
    const logPattern = /^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+)\s*\|([^|]*)\|\s*(INFO|WARN|ERROR|DEBUG|SUCCESS)\s*\|\s*(.*)$/i
    
    const match = logString.match(logPattern)
    
    if (match) {
      const [, timestampStr, source, levelStr, message] = match
      
      // 解析时间戳
      const timestamp = new Date(timestampStr.replace(/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})\.(\d+)/, '$1T$2.$3'))
      
      // 标准化日志级别
      const level = levelStr.toLowerCase() as LogEntry['level']
      
      return {
        id: `${index}-${Date.now()}`,
        timestamp: isNaN(timestamp.getTime()) ? new Date() : timestamp,
        level: ['info', 'warn', 'error', 'debug', 'success'].includes(level) ? level : 'info',
        message: message.trim(),
        source: source.trim()
      }
    }
    
    // 如果解析失败，返回原始字符串作为消息
    return {
      id: `${index}-${Date.now()}`,
      timestamp: '',
      level: 'info',
      message: logString,
      source: 'unknown'
    }
  }

  // 处理日志数据
  const processedLogs: LogEntry[] = logs.map((log, index) => {
    if (typeof log === 'string') {
      return parseLogString(log, index)
    }
    return log
  })

  // 过滤日志
  const filteredLogs = filterLevel 
    ? processedLogs.filter(log => filterLevel.includes(log.level))
    : processedLogs

  // 自动滚动到底部
  useEffect(() => {
    if (autoScroll && !isUserScrolling && containerRef.current) {
      containerRef.current.scrollTop = containerRef.current.scrollHeight
    }
  }, [filteredLogs, autoScroll, isUserScrolling])

  // 检测用户滚动
  const handleScroll = () => {
    if (!containerRef.current) return
    
    const { scrollTop, scrollHeight, clientHeight } = containerRef.current
    const isAtBottom = scrollTop + clientHeight >= scrollHeight - 10
    
    setIsUserScrolling(!isAtBottom)
  }

  // 获取日志级别的颜色方案
  const getLevelColorScheme = (level: LogEntry['level']) => {
    const schemes = {
      info: 'blue',
      warn: 'yellow',
      error: 'red',
      debug: 'gray',
      success: 'green'
    }
    return schemes[level] || 'blue'
  }

  // 获取日志级别的背景色
  const getLevelBg = (level: LogEntry['level']) => {
    const bgs = {
      info: 'blue.50',
      warn: 'yellow.50',
      error: 'red.50',
      debug: 'gray.50',
      success: 'green.50'
    }
    return bgs[level]
  }

  // 格式化时间戳
  const formatTimestamp = (timestamp: Date) => {
    return timestamp.toLocaleTimeString('zh-CN', {
      hour12: false,
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      fractionalSecondDigits: 3
    })
  }

  const scrollToBottom = () => {
    if (containerRef.current) {
      containerRef.current.scrollTop = containerRef.current.scrollHeight
      setIsUserScrolling(false)
    }
  }

  return (
    <Box border="1px" borderColor="gray.200" borderRadius="lg">
      {/* 头部工具栏 */}
      <Flex
        align="center"
        justify="space-between"
        p={3}
        borderBottom="1px"
        borderColor="gray.200"
        borderTopRadius="lg"
      >
        <Text fontSize="sm" fontWeight="medium">
          实时日志
        </Text>
        <HStack spacing={3}>
          <Text fontSize="xs" color="gray.500">
            {filteredLogs.length} 条记录
          </Text>
          {!isUserScrolling && autoScroll && (
            <HStack spacing={1}>
              <Box
                w={'70%'}
                h={'full'}
                borderRadius="full"
                animation="pulse 2s infinite"
              />
              <Text fontSize="xs" color="green.500">
                自动滚动
              </Text>
            </HStack>
          )}
        </HStack>
      </Flex>

      {/* 日志内容 */}
      <Box
        ref={containerRef}
        overflowY="auto"
        p={3}
        fontFamily="mono"
        fontSize="sm"
        maxHeight={maxHeight}
        onScroll={handleScroll}
      >
        {filteredLogs.length === 0 ? (
          <Flex justify="center" align="center" py={8}>
            <Text color="gray.500">暂无日志数据</Text>
          </Flex>
        ) : (
          <VStack spacing={1} align="stretch">
            {filteredLogs.map((log) => (
              <Box
                key={log.id}
                p={2}
                borderRadius="md"
                // bg={getLevelBg(log.level)}
              >
                <HStack spacing={2} align="flex-start">
                  {showTimestamp && (
                    <Text
                      color="gray.500"
                      fontSize="xs"
                      whiteSpace="nowrap"
                      fontFamily="mono"
                    >
                      {log.timestamp instanceof Date
                        ? formatTimestamp(log.timestamp)
                        : log.timestamp}
                    </Text>
                  )}
                  
                  {showLevel && (
                    <Badge
                      colorScheme={getLevelColorScheme(log.level)}
                      fontSize="xs"
                      textTransform="uppercase"
                    >
                      {log.level}
                    </Badge>
                  )}
                  
                  {showSource && log.source && log.source !== 'unknown' && (
                    <Badge
                      variant="outline"
                      colorScheme="gray"
                      fontSize="xs"
                      fontFamily="mono"
                    >
                      {log.source}
                    </Badge>
                  )}
                  
                  <Text flex={1} fontSize="xs" wordBreak="break-words">
                    {log.message}
                  </Text>
                </HStack>
              </Box>
            ))}
          </VStack>
        )}
      </Box>

      {/* 底部状态栏 */}
      {isUserScrolling && autoScroll && (
        <Box p={3} borderTop="1px" borderColor="gray.200" bg="gray.50">
          <Button
            size="xs"
            variant="link"
            colorScheme="blue"
            onClick={scrollToBottom}
          >
            滚动到底部
          </Button>
        </Box>
      )}
    </Box>
  )
}

export default LogBox